package org.zoomdev.zoom.dao.meta;

import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.driver.SqlDriver;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;

public final class LazyDatabaseMeta {
    private final ConcurrentHashMap<String, TableKeyMeta> cache = new ConcurrentHashMap<>();


    public LazyDatabaseMeta() {

    }

    public TableKeyMeta get(DataSource dataSource, SqlDriver driver, String table) {
        return cache.computeIfAbsent(table.toUpperCase(), k -> {
            try (Connection connection = dataSource.getConnection()) {
                TableKeyMeta tableMeta = new TableKeyMeta();
                tableMeta.setName(table);
                driver.fill(connection, tableMeta);
                return tableMeta;
            } catch (SQLException e) {
                throw new DaoException(e);
            }
        });
    }
}
